/**
 * 身份证方法校验
 */

// 根据身份证号码获取性别
export function getSexByIdCard(IdCard) {
  // 一代身份证号码的第15位是性别的判断，奇数表示男性，偶数表示女性；
  // 二代身份证号码的第17位是性别的判断，奇数表示男性，偶数表示女性。
  if (parseInt(IdCard.substr(16, 1)) % 2 === 0 && IdCard.length === 18) {
    return 2;
  } else if (parseInt(IdCard.substr(14, 1)) % 2 === 0 && IdCard.length === 15) {
    return 2;
  } else {
    return 1;
  }
}



// 根据身份证号码获取年龄
export function getAge(idCard) {
  let birthday = getBirthday(idCard)
  const today = new Date();
  const birthDate = new Date(birthday);
  let age = '';
  if (today.getFullYear() > birthDate.getFullYear()) {
    age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
  }
  return age;
}


// 根据身份证获取出生日期 YYYY-MM
export function getBirthdayNoDay(idCard) {
  let birthday = '';
  if (idCard.length === 15) {
    birthday = '19' + idCard.substring(6, 10);
  } else if (idCard.length === 18) {
    birthday = idCard.substring(6, 12);
  }
  return birthday.replace(/(.{4})(.{2})/, '$1-$2')
}


// 获取出生日期  YYYY-MM-DD
export function getBirthday(idCard) {
  let birthday = '';
  if (idCard.length === 15) {
    birthday = '19' + idCard.substring(6, 12);
  } else if (idCard.length === 18) {
    birthday = idCard.substring(6, 14);
  }
  return birthday.replace(/(.{4})(.{2})(.{2})/, '$1-$2-$3')
}